package com.yang.system.domain.orgMng.org.validator;

import com.yang.system.domain.common.exception.BusinessException;
import com.yang.system.domain.orgMng.org.OrgRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static org.apache.logging.log4j.util.Strings.isBlank;

@Component
public class OrgNameValidator {
    private final OrgRepository orgRepository;
    @Autowired
    public OrgNameValidator(OrgRepository orgRepository) {
        this.orgRepository = orgRepository;
    }

    // 校验组织名称的规则分组
    private void verifyOrgName(Long tenant, String name, Long superiorId) {
        orgNameShouldNotEmpty(name);
        nameShouldNotDuplicatedInSameSuperior(tenant, superiorId, name);
    }

    // 组织必须有名称
    public void orgNameShouldNotEmpty(String name) {
        if (isBlank(name)) {
            throw new BusinessException("组织没有名称！");
        }
    }

    public void nameShouldNotDuplicatedInSameSuperior(Long tenantId, Long superiorId, String name) {
        // 同一个组织下的下级组织不能重名
        if (orgRepository.existsBySuperiorAndName(tenantId, superiorId, name)) {
            throw new BusinessException("同一上级下已经有名为'"
                    + name + "'的组织存在！");
        }
    }

    public void verify(Long tenantId, String name, Long superiorId) {
        verifyOrgName(tenantId, name, superiorId);
    }
}
